package com.chucang.shucang.oms.listener;

import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.common.mq.to.BlindBoxOrderBaseTO;
import com.chucang.shucang.common.mq.to.CollectionOrderBaseTO;
import com.chucang.shucang.oms.service.BlindBoxOrderBaseService;
import com.chucang.shucang.oms.service.CollectionOrderBaseService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/13 15:01
 * @description
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RabbitListener(queues = RabbitConstant.ORDER_PANIC_PURCHASE_RELEASE_QUEUE)
public class PanicPurchaseOrderReleaseListener {

    private final BlindBoxOrderBaseService blindBoxOrderBaseService;
    private final CollectionOrderBaseService collectionOrderBaseService;

    @RabbitHandler
    public void collectionOrderReleaseListener(CollectionOrderBaseTO collectionOrderBase, Channel channel, Message message) throws IOException {
        try {
            collectionOrderBaseService.cancelCollectionOrder(collectionOrderBase.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("解锁藏品库存失败！errMsg===>{}", e.getMessage(), e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void blindBoxOrderReleaseListener(BlindBoxOrderBaseTO blindBoxOrderBase, Channel channel, Message message) throws IOException {
        try {
            blindBoxOrderBaseService.cancelBlindBoxOrder(blindBoxOrderBase.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("解锁盲盒库存失败！errMsg===>{}", e.getMessage(), e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
